package com.tuozixuan.caffeine;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;

public class AutoAsyncDemo {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		
		// 去异步的封装一段同步操作来生成缓存元素
		AsyncLoadingCache<String, String> cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).maximumSize(10_000).buildAsync(key -> {
			 return "lisi";
		 });
		// 构建一个异步缓存元素操作并返回一个future
		AsyncLoadingCache<String, String> cache1 = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).maximumSize(10_000).buildAsync((key, executor) -> {
			 return null;
		 });
		
		String key = "name";
		
		// 查找缓存元素，如果其不存在，将会异步进行生成
		CompletableFuture<String> name = cache.get(key);
		System.out.println("name:" + name.get());
		
		// 批量查找缓存元素，如果其不存在，将会异步进行生成
		List<String> keys = Arrays.asList(key);
		CompletableFuture<Map<String, String>> map = cache.getAll(keys);
		System.out.println("map:" + map.get());
		
	}

}
